package com.example.test02;

import android.graphics.Typeface;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import androidx.appcompat.widget.Toolbar;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Toolbar toolbar = findViewById(R.id.topBar);
        setSupportActionBar(toolbar);

        // 获取自定义的 TextView 并设置标题居中和加粗
        TextView titleTextView = toolbar.findViewById(R.id.title);
        if (titleTextView != null) {
            titleTextView.setGravity(Gravity.CENTER);
            titleTextView.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
        }

        BottomNavigationView navigation = findViewById(R.id.bottom_navigation);
        navigation.setOnItemSelectedListener(item -> {
            Fragment selectedFragment = null;
            String topbarTitle = "";
            if (item.getItemId() == R.id.navigation_guard) {
                selectedFragment = new GuardFragment();
                topbarTitle = "安全守护";
            } else if (item.getItemId() == R.id.navigation_message) {
                selectedFragment = new NewsFragment();
                topbarTitle = "消息";
            } else if (item.getItemId() == R.id.navigation_profile) {
                selectedFragment = new MyFragment();
                topbarTitle = "我的";
            }
            if (selectedFragment != null) {
                showFragment(selectedFragment, topbarTitle);
            }
            return true;
        });

        // 默认选中 guard 图标
        navigation.getMenu().findItem(R.id.navigation_guard).setChecked(true);
        showFragment(new GuardFragment(), "安全守护");
    }

    private void showFragment(Fragment fragment, String title) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.fragment_container, fragment);
        fragmentTransaction.commitAllowingStateLoss();

        // 获取 Toolbar 中的 TextView 并设置标题
        TextView titleTextView = findViewById(R.id.title);
        if (titleTextView != null) {
            titleTextView.setText(title);
        }

        // 如果需要更新 ActionBar 的标题，取消以下注释
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setTitle(title);
        }
    }

}
